package com.wephone.Student.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.wephone.Student.util.Utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.wephone.Student.R;

import com.wephone.Student.bean.BaseResponse;
import com.wephone.Student.bean.GroupInfoDetailResponse;
import com.wephone.Student.bean.GroupResponse;
import com.wephone.Student.bean.data.GroupInfo;
import com.wephone.Student.bean.data.UserInfoData;
import com.wephone.Student.huanxin.activity.ChatActivity;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.RoundImageView;
import com.wephone.Student.util.Util;



public class GroupInfoDetailActivity extends BaseActivity {
	private GroupInfo groupData;
	private TextView group_name;
	private TextView group_desc;
	private TextView group_num;
	private TextView group_id;
	private TextView group_type;
	private TextView group_loc;
	private ImageView group_pic;
	private ImageView now_num_line;
	
	private LinearLayout bottom_join_in,bottom_no_join,member_list;
	private RelativeLayout groupMember;
	private Button btn_send_msg,btn_manage_setting;
	private Boolean isIn = false;
	
	private ArrayList<UserInfoData> users = new ArrayList<UserInfoData>();
	
	//获取详情
	private MyResponseHandler getHandler(){
		MyResponseHandler handler = new MyResponseHandler(GroupInfoDetailActivity.this,GroupInfoDetailResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				findViewById(R.id.progressBar).setVisibility(View.GONE);
				if(getDataSuccess){
					Object data = ((GroupInfoDetailResponse)response).getData();
					Gson gson = new Gson();
					try {
						String string = gson.toJson(data);
						JSONObject dataObject = new JSONObject(string);
						JSONArray users_arr = dataObject.getJSONArray("user");
						for (int i = 0; i < users_arr.length(); i++) {
							JSONObject obj = users_arr.getJSONObject(i);
							JSONObject uinfo = obj.getJSONObject("uinfo");
							UserInfoData userInfoData = (UserInfoData)gson.fromJson(uinfo.toString(), UserInfoData.class);
							String currentid = BaseActivity.getMyInfo(getApplicationContext()).getuId();
							if(userInfoData.getuId().equals(currentid)){
								bottom_join_in.setVisibility(View.VISIBLE);
								isIn = true;
							}
							users.add(userInfoData);
						}
						if(!isIn){
							bottom_no_join.setVisibility(View.VISIBLE);
						}
						if(users.size()>0){
							for(int i=0;i<users.size();i++){
								if(i>9){
									break;
								}
								UserInfoData userData = (UserInfoData) users.get(i);
								RoundImageView img = new RoundImageView(getApplicationContext());
						        LinearLayout.LayoutParams viewParamsCenter = new LinearLayout.LayoutParams(
						                (int)Util.convertDpToPixel(32, getApplicationContext()), (int)Util.convertDpToPixel(32, getApplicationContext()));
						        viewParamsCenter.leftMargin=(int)Util.convertDpToPixel(15, getApplicationContext());
						        img.setImageResource(R.drawable.ic_launcher);
						        img.setLayoutParams(viewParamsCenter);
						        member_list.addView(img);
						        imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+userData.getuIcon(), img);
							}
						}
						
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		};
		return handler;
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_group_info_detail);
		
		Bundle bundle = getIntent().getExtras();
		if(bundle!=null){
			groupData = (GroupInfo)bundle.getSerializable("groupData");
			init();
		}else{
			finish();
			Toast.makeText(getApplicationContext(), "数据异常", Toast.LENGTH_SHORT).show();
		}
	}
	
	private void init(){
		group_name = (TextView)findViewById(R.id.group_name);
		group_name.setText(groupData.getName());
		
		group_desc = (TextView)findViewById(R.id.group_desc);
		group_desc.setText(groupData.getContent());
		group_num = (TextView)findViewById(R.id.group_num);
		group_num.setText(groupData.getNownum()+"/"+groupData.getMaxnum());
		group_id = (TextView)findViewById(R.id.group_id);
		group_id.setText(groupData.getGroupid());
		group_type = (TextView)findViewById(R.id.group_type);
		group_type.setText(groupData.getType());
		group_loc = (TextView)findViewById(R.id.group_loc);
		group_loc.setText(groupData.getClog());
		group_pic = (ImageView)findViewById(R.id.group_pic);
		
		bottom_join_in = (LinearLayout)findViewById(R.id.bottom_join_in);
		bottom_no_join = (LinearLayout)findViewById(R.id.bottom_no_join);
		
		bottom_join_in.setVisibility(View.GONE);
		bottom_no_join.setVisibility(View.GONE);
		
		member_list = (LinearLayout)findViewById(R.id.member_list);
		
		btn_manage_setting = (Button)findViewById(R.id.btn_manage_setting);
		btn_send_msg = (Button)findViewById(R.id.btn_send_msg);
		
		now_num_line = (ImageView)findViewById(R.id.now_num_line);
		
		float real_width = Util.getScreenWidth(getApplicationContext())*Integer.parseInt(groupData.getNownum())/Integer.parseInt(groupData.getMaxnum());
		now_num_line.getLayoutParams().width = (int)Util.convertDpToPixel(real_width, getApplicationContext());
		
		groupMember = (RelativeLayout)findViewById(R.id.groupMember);
		
		groupMember.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getApplicationContext(),GroupMembersActivity.class);
				//intent.putSerializable("groupData", groupData);
				Bundle bundle = new Bundle();
				bundle.putSerializable("groupData", groupData);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
		
		btn_manage_setting.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Bundle bundle = new Bundle();
				bundle.putSerializable("groupData", groupData);
				
				Intent intent = new Intent(GroupInfoDetailActivity.this,GroupSettingActivity.class);
				intent.putExtras(bundle);
				startActivityForResult(intent,101);
			}
		});
		
		btn_send_msg.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				//ChatActivity.toUserInfo = groupData;
				Intent intent = new Intent(getApplicationContext(),ChatActivity.class);
				intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP);
				intent.putExtra("groupId", groupData.getGroupid());
				Bundle bundle = new Bundle();
				bundle.putSerializable("groupData", groupData);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
		
		findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		Button btn_join_in =(Button)findViewById(R.id.btn_join_in);
		btn_join_in.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Bundle bundle = new Bundle();
				bundle.putSerializable("groupData", groupData);
				Intent intent = new Intent(getApplicationContext(),GroupJoinActivity.class);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
		
		if(!TextUtils.isEmpty(groupData.getPic())){
			DisplayImageOptions options = new DisplayImageOptions.Builder()
	        .showStubImage(R.drawable.bg_title_bar)
	        .showImageOnFail(R.drawable.bg_title_bar)
	        .bitmapConfig(Bitmap.Config.ARGB_8888)
	        .cacheInMemory()
	        .cacheOnDisc()
//	        .displayer(new RoundedBitmapDisplayer(1000))
	        .build();
//			imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+userData.getuIcon(), itemImage, options);
			imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+groupData.getPic(), group_pic, options,new ImageLoadingListener() {
			
				@Override
				public void onLoadingCancelled(String arg0, View arg1) {
					// TODO Auto-generated method stub
					
				}
				@Override
				public void onLoadingComplete(String arg0, View arg1,
						Bitmap arg2) {
					// TODO Auto-generated method stub
					Bitmap tempBitmap = Utils.getFixedBitMap(arg2,getApplicationContext(),1);
					if(tempBitmap != null) {
						group_pic.setImageBitmap(tempBitmap);
					}
				}

				@Override
				public void onLoadingFailed(String arg0, View arg1,
						FailReason arg2) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onLoadingStarted(String arg0, View arg1) {
					// TODO Auto-generated method stub
					
				}
			});
		}
		//获取群组详情
		findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
		RequestParams params2 = new RequestParams();
		params2.put("groupid", groupData.getGroupid());
		params2.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
		HttpClient.getInstance().get(Constants.API_GET_CHART_DETAIL, params2, getHandler());
	}	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == 101 && resultCode==110){
			finish();
		}
	}
	private DisplayImageOptions options = new DisplayImageOptions.Builder()
    .showStubImage(R.drawable.liuxuequan_image_default)
    .showImageOnFail(R.drawable.liuxuequan_image_default)
    .bitmapConfig(Bitmap.Config.ARGB_8888)
    .cacheInMemory()
    .cacheOnDisc()
//    .displayer(new RoundedBitmapDisplayer(1000))
    .build();
	
}
